﻿Imports System.Data.SqlClient

Public Class FormBackup

    Private Sub FormBackup_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub btnUbicacion_Click(sender As System.Object, e As System.EventArgs) Handles btnUbicacion.Click
        SaveFileDialog1.Filter = "bak files (*.bak)|*.bak"
        SaveFileDialog1.AddExtension = True
        If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
            txtUbicacion.Text = SaveFileDialog1.FileName
        End If
    End Sub

    Private Sub btnCancelar_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Function ValidarCampos(ubicacion As Boolean) As Boolean

        Dim controlCampos As Boolean = False

        If txtUsuario.Text = "" Then
            ErrorProvider1.SetError(txtUsuario, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtUsuario, "")
        End If

        If txtContrasena.Text = "" Then
            ErrorProvider1.SetError(txtContrasena, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtContrasena, "")
        End If

        If txtBaseDatos.Text = "" Then
            ErrorProvider1.SetError(txtBaseDatos, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtBaseDatos, "")
        End If

        If txtServer.Text = "" Then
            ErrorProvider1.SetError(txtServer, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtServer, "")
        End If

        If ubicacion Then
            If txtUbicacion.Text = "" Then
                ErrorProvider1.SetError(txtUbicacion, "Campo obligatorio")
                controlCampos = True
            Else
                ErrorProvider1.SetError(txtUbicacion, "")
            End If
        End If
        '
        Return controlCampos

    End Function

    Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click
        Try

            If ValidarCampos(True) Then
                txtUsuario.Focus()
                Exit Sub
            End If

            Dim connStr As String = "data source=" & txtServer.Text & ";initial catalog=" & txtBaseDatos.Text & ";integrated security=false;persist security info=false;user id=" & txtUsuario.Text & ";password=" & txtContrasena.Text & ";multipleactiveresultsets=true;connect timeout=120"

            Using conn As New SqlConnection(connStr)
                Dim sqlStmt As String = [String].Format("BACKUP DATABASE " & txtBaseDatos.Text & " TO DISK='{0}'", txtUbicacion.Text)

                Using bu2 As New SqlCommand(sqlStmt, conn)
                    conn.Open()
                    bu2.ExecuteNonQuery()
                    conn.Close()

                    MessageBox.Show("Backup ejecutado con exito.", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End Using
            End Using

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Backup error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub btnConexion_Click(sender As System.Object, e As System.EventArgs) Handles btnConexion.Click
        Try
            If ValidarCampos(False) Then
                txtUsuario.Focus()
                Exit Sub
            End If

            Dim connStr As String = "data source=" & txtServer.Text & ";initial catalog=" & txtBaseDatos.Text & ";integrated security=false;persist security info=false;user id=" & txtUsuario.Text & ";password=" & txtContrasena.Text & ";multipleactiveresultsets=true;connect timeout=120"

            Using conn As New SqlConnection(connStr)
                Dim sqlStmt As String = [String].Format("BACKUP DATABASE " & txtBaseDatos.Text & " TO DISK='{0}'", txtUbicacion.Text)

                Using bu2 As New SqlCommand(sqlStmt, conn)
                    conn.Open()
                    conn.Close()
                    MessageBox.Show("Conexion establecida con exito.", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End Using

            End Using

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Backup error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub btnEjecutar_Click(sender As System.Object, e As System.EventArgs) Handles btnEjecutar.Click
        Try

            If MessageBox.Show("Esta seguro de eliminar los registros?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                Exit Sub
            End If

            Dim usu As New Class_RC_Controller.rc_Mantenimiento()
            Dim query As String = ""
            Dim resul As Integer = 0
            Dim queryFecha As String = " between CONVERT(datetime, '" & fechaInicio.Value.Year.ToString() & "-" & fechaInicio.Value.Month.ToString().PadLeft(2, "0") & "-" & fechaInicio.Value.Day.ToString().PadLeft(2, "0") & _
                " 00:00:00') and CONVERT(datetime, '" & fechaInicio.Value.Year.ToString() & "-" & fechaFin.Value.Month.ToString().PadLeft(2, "0") & "-" & fechaFin.Value.Day.ToString().PadLeft(2, "0") & " 23:59:59') "

            If cboTablas.Text = "PEDIDOS" Then

                query = "DELETE FROM NOTAS WHERE fecha " & queryFecha

                resul = usu.limpiarTablas(oiml.dbConn, query, oiml.idUsuario)

                If resul = 0 Then
                    If Not usu.MessageError Is Nothing Then
                        Throw New Exception(usu.MessageError.Message)
                    End If

                Else
                    MessageBox.Show("Registros eliminados con exito, cantidad: " & resul, "Mantenimiento", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If

            ElseIf cboTablas.Text = "COMPRAS" Then

                query = "DELETE FROM COMPRAS WHERE fecha " & queryFecha

                resul = usu.limpiarTablas(oiml.dbConn, query, oiml.idUsuario)

                If resul = 0 Then
                    If Not usu.MessageError Is Nothing Then
                        Throw New Exception(usu.MessageError.Message)
                    End If

                Else
                    MessageBox.Show("Registros eliminados con exito, cantidad: " & resul, "Mantenimiento", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If

            ElseIf cboTablas.Text = "COBROS" Then

                query = "DELETE FROM COBROS WHERE fechaCobro " & queryFecha

                resul = usu.limpiarTablas(oiml.dbConn, query, oiml.idUsuario)

                If resul = 0 Then
                    If Not usu.MessageError Is Nothing Then
                        Throw New Exception(usu.MessageError.Message)
                    End If

                Else
                    MessageBox.Show("Registros eliminados con exito, cantidad: " & resul, "Mantenimiento", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If

            ElseIf cboTablas.Text = "VENTAS" Then

                query = "DELETE FROM VENTAS WHERE fecha " & queryFecha

                resul = usu.limpiarTablas(oiml.dbConn, query, oiml.idUsuario)

                If resul = 0 Then
                    If Not usu.MessageError Is Nothing Then
                        Throw New Exception(usu.MessageError.Message)
                    End If

                Else
                    MessageBox.Show("Registros eliminados con exito, cantidad: " & resul, "Mantenimiento", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If

            ElseIf cboTablas.Text = "PRODUCTOS (ENTRADAS / SALIDAS)" Then

            ElseIf cboTablas.Text = "MATERIALES (ENTRADAS / SALIDAS)" Then

            ElseIf cboTablas.Text = "LOG" Then

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Clean error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub

   
    Private Sub btnSelecRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelecRestore.Click
        OpenFileDialog1.Filter = "bak files (*.bak)|*.bak"
        OpenFileDialog1.AddExtension = True
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            txtUbicacion.Text = OpenFileDialog1.FileName
        End If
    End Sub

    Private Sub btnRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestore.Click
        Try

            If ValidarCampos(True) Then
                txtUsuario.Focus()
                Exit Sub
            End If

            Dim connStr As String = "data source=" & txtServer.Text & ";initial catalog=" & txtBaseDatos.Text & ";integrated security=false;persist security info=false;user id=" & txtUsuario.Text & ";password=" & txtContrasena.Text & ";multipleactiveresultsets=true;connect timeout=120"

            Using conn As New SqlConnection(connStr)
                Dim sqlStmt As String = [String].Format("RESTORE DATABASE " & txtBaseDatos.Text & " FROM  DISK = N'" & txtUbicacion.Text & "' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10")
                'RESTORE DATABASE [sistemaRC] FROM  DISK = N'C:\SistemaRC\Versiones BD\sistemaRCv2.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
                Using bu2 As New SqlCommand(sqlStmt, conn)
                    conn.Open()
                    bu2.ExecuteNonQuery()
                    conn.Close()

                    MessageBox.Show("Restauracion ejecutada con exito.", "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End Using
            End Using

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Backup error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
    End Sub
End Class